package threads;

import java.io.*;
import java.net.*;

import android.os.Handler;

import sjtu.ChatClient.HandlerConstants;

public class ReceiveExpressionThread implements Runnable {
	private int port;
	private DatagramSocket socket;
	private boolean isStopped = false;
	private Handler handler;
	
	public ReceiveExpressionThread(int port, Handler handler){
		this.port = port;
		socket = null;
		this.handler = handler;
	}
	
	private synchronized boolean isStopped(){
		return isStopped;
	}
	
	public synchronized void stop(){
		isStopped = true;
		socket.close();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			socket = new DatagramSocket(port);
			byte [] buffer = new byte [100];
			while(isStopped() == false){
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				socket.receive(packet);
				byte [] data = packet.getData();
				int result = (int) (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]);
				switch(result){
				case HandlerConstants.EXPRESSION_HAPPY:
					handler.obtainMessage(HandlerConstants.EXPRESSION_HAPPY).sendToTarget();
					break;
				case HandlerConstants.EXPRESSION_NEUTRAL:
					handler.obtainMessage(HandlerConstants.EXPRESSION_NEUTRAL).sendToTarget();
					break;
				case HandlerConstants.EXPRESSION_SAD:
					handler.obtainMessage(HandlerConstants.EXPRESSION_SAD).sendToTarget();
					break;
				default:
					handler.obtainMessage(HandlerConstants.EXPRESSION_NULL).sendToTarget();
					break;
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
